<template>
  <div class="edu-page-warp">
    <inner-breadcrumb v-model="key" 
      :label-args="{topTitle:this.topTitle, addTitle: this.addTitle, detailTitle: this.detailTitle}"
      :path="{
      label : '{topTitle}',
      key: 'list',
      children:[
        {
          key: 'add',
          label:'{addTitle}'
        },
         {
           key: 'detail',
          label:'{detailTitle}'
          }
        ]
    }"/>
    <div class="edu-page-warp" v-if="key=='list'">
    <condition-card @reset="reset" @search="searchList" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('Parameter.personnelCollenge')">
              <DictSelect v-model="queryParams.personnelCollege" :data="options.faculty" filterable></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('Parameter.tutorCollenge')">
              <DictSelect v-model="queryParams.faculty" :data="options.faculty" filterable></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('label.major')" v-if="tutorType ==2">
              <MajorSelect :faculty="queryParams.faculty" v-model="queryParams.major"></MajorSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('school.school')" v-if="tutorType ==1">
              <DictSelect v-model="queryParams.schoolId" :data="options.school" ></DictSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('Parameter.schoolMajor')" v-if="tutorType ==1">
              <SchoolMajorSelect  :schoolId="queryParams.schoolId" v-model="queryParams.major" ></SchoolMajorSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('Parameter.title')">
              <DictSelect v-model="queryParams.title" :data="options.title" filterable></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('tutorList.status')">
              <DictSelect v-model="queryParams.status" :data="options.status"></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('tutorList.isAcrossMajor')" v-if="tutorType ==2">
              <DictSelect v-model="queryParams.isAcross" :data="options.isAcross"></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('tutorList.isAcross')" v-if="tutorType ==1">
               <DictSelect v-model="queryParams.isAcross" :data="options.isAcross"></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('tutorList.employmentYear')" >
               <SchoolYear v-model="queryParams.grade" :showAll="false" :clearable="false"></SchoolYear>
            </el-form-item>
          </el-col>
        </el-row>
    </condition-card>
    <el-card shadow="never">
      <div class="edu-page-title">{{topTitle}}</div>
      <div class="edu-opertion-bar">
        <div class="float-left">
            <KeywordInput v-model="queryParams.condition" @enter="searchList" placeholder="请输入工号或姓名搜索"></KeywordInput>
        </div>
        <!-- <div class="float-right">
           <el-button @click="exportTutor" v-premit="export_tutor">{{$t('message.export')}} </el-button>
           <el-dropdown @command="importRecord">
                <el-button v-premit="import_tutor">
                  {{$t('message.import')}}<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="importIn">{{$t('message.import')}}</el-dropdown-item>
                  <el-dropdown-item command="importOut">{{$t('message.down')}}</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown @command="importRecord">
                <el-button type="primary" v-premit="extend_tutor">
                 {{$t('tutorGuide.extendedImport')}}<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="renewalIn">{{$t('message.import')}}</el-dropdown-item>
                  <el-dropdown-item command="renewalOut">{{$t('message.down')}}</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
          <el-button @click="updateRecord(null)" v-premit="add_tutor" type="primary">{{$t('common.btn.add')}}</el-button>
        </div> -->
      </div>
      <edu-table url="/api/welcomeservice/tutorList/teacher/list" ref="mainTable" :order="false" :selection="true">
        <el-table-column :label="$t('Parameter.jobNumber')" prop="teacherCode"/>
        <el-table-column :label="$t('label.stuName')" prop="teacherName"/>
        <el-table-column :label="$t('label.sex')" prop="sexI18n" />
        <el-table-column :label="$t('Parameter.title')" prop="titleI18n"  show-overflow-tooltip/>
        <el-table-column :label="$t('Parameter.personnelCollenge')" prop="personnelCollegeI18n" :render-header="labelHead" show-overflow-tooltip/>
        <el-table-column :label="$t('Parameter.tutorCollenge')" prop="facultyI18n"  :render-header="labelHead" show-overflow-tooltip/>
        <el-table-column :label="$t('label.major')" prop="majorI18n" v-if="tutorType ==2"  show-overflow-tooltip/>
        <el-table-column :label="$t('school.school')" prop="school" v-if="tutorType ==1"  show-overflow-tooltip/>
        <el-table-column :label="$t('Parameter.schoolMajor')" prop="majorI18n" v-if="tutorType ==1"  show-overflow-tooltip/>
        <el-table-column :label="$t('tutorList.planNumber')" prop="planNum" >
          <template slot-scope="scope">
          <span>{{scope.row.planNum ? scope.row.planNum:0}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('tutorList.actualNumber')" prop="actNum">
          <template slot-scope="scope">
          <span>{{scope.row.actNum ? scope.row.actNum:0}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('tutorList.status')" prop="status" >
          <template slot-scope="scope" >
            <el-tag v-if="scope.row.status == 1" type="success">{{$t('tutorList.effective')}}</el-tag>
            <el-tag v-else>{{$t('tutorList.invalid')}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('message.remark')" prop="remark" show-overflow-tooltip/>
        <el-table-column :label="$t('message.operating')">
          <template slot-scope="scope" fixed="right">
            <el-button type="text"  @click="updateRecord(scope.row)" size="mini" v-premit="edit_tutor">{{$t('message.edit')}}</el-button>
            <!-- <el-button type="text"  @click="detail(scope.row)" size="mini" v-premit="detail_tutor">{{$t('message.detail')}}</el-button> -->
          </template>
        </el-table-column>
      </edu-table>
    </el-card>
    </div>
<!-- 编辑 -->
    <div class="edu-page-warp"  v-if="key == 'add'">
     <el-card shadow="never">
       <div class="edu-page-title">{{addTitle}}</div>
       <hr />
      <el-form :model="createForm" ref="createForm" label-width="100px" label-suffix=":" :rules="rules">
        <el-row>
          <el-col :span="4" >
              <el-upload
                class="avatar-uploader"
                action="/api/commonservice/obsfile/uploadfile"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :data="{bucketname: 'face', folderpath: 'file'}"
                :file-list="fileList"
                >
                <img v-if="createForm.photo" :src="imgUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
          </el-col>
          <el-col :span="20">
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('Parameter.jobNumber')" prop="teacherCode">
                    <el-input v-model="createForm.teacherCode" @keyup.enter.native="getTeacherfo" @change="getTeacherfo"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('label.stuName')" prop="teacherName" >
                    <el-input v-model="createForm.teacherName" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('label.sex')" prop="sex" >
                    <DictSelect v-model="createForm.sex" :data="options.sex" :disabled="true"></DictSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('Parameter.title')" prop="title">
                    <DictSelect v-model="createForm.title" :data="options.title" :disabled="true"></DictSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('Parameter.personnelCollenge')" prop="personnelCollege">
                   <DictSelect v-model="createForm.personnelCollege" :data="options.faculty" :disabled="true"></DictSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('Parameter.tutorCollenge')" prop="faculty">
                    <DictSelect v-model="createForm.faculty" :data="options.faculty" :disabled="editFaculty"></DictSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('label.major')" prop="major" v-if="tutorType ==2 && !isMultiple">
                  <MajorSelect :faculty="createForm.faculty" v-model="createForm.majors" :multiple="true" @load-done="getAllMajor"></MajorSelect>
                  </el-form-item>
                </el-col>
                  <!-- 编辑单选 -->
                <el-col :span="12">
                  <el-form-item :label="$t('label.major')" prop="major" v-if="tutorType ==2 && isMultiple">
                  <MajorSelect :faculty="createForm.faculty" v-model="createForm.major" :clearable="false" ></MajorSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('school.school')" prop="schoolId" v-if="tutorType ==1">
                  <DictSelect v-model="createForm.schoolId" :data="options.school" ></DictSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('Parameter.schoolMajor')" prop="majors" v-if="tutorType ==1 && !isMultiple " >
                    <SchoolMajorSelect :schoolId="createForm.schoolId" v-model="createForm.majors"  :multiple="true" @load-done="getSchoolMajor"></SchoolMajorSelect>
                  </el-form-item>
                </el-col>
                <!-- 编辑单选 -->
                <el-col :span="12">
                  <el-form-item :label="$t('Parameter.schoolMajor')" prop="major" v-if="tutorType ==1 && isMultiple" >
                    <SchoolMajorSelect :schoolId="createForm.schoolId" v-model="createForm.major"  :clearable="false"></SchoolMajorSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('tutorList.status')" prop="status">
                    <DictSelect v-model="createForm.status" :data="options.status"></DictSelect>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('tutorList.employmentYear')"  prop="grade">
                    <SchoolYear v-model="createForm.grade" :showAll="false"></SchoolYear>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('tutorList.officePhone')" prop="officePhone">
                    <el-input v-model="createForm.officePhone" maxlength="32"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('tutorList.telePhone')" prop="telPhone">
                    <el-input v-model="createForm.telPhone" maxlength="32"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('tutorList.email')" prop="email">
                    <el-input v-model="createForm.email" maxlength="64"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('tutorList.tutorIntroduction')" prop="introduce" >
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="createForm.introduce" clearable maxlength="2048" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('message.remark')" prop="remark">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="createForm.remark" clearable maxlength="255" show-word-limit></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div  class="float-right">
        <el-button @click="reback(createForm)">{{$t('message.return')}}</el-button>
        <el-button type="primary" @click="submitForm">{{$t('message.save')}}</el-button>
      </div>
     </el-card>
    </div>
  </div>
</template>
<script>

import { queryDic } from "common/src/api/dictionary";
import APIs from "common/src/api/welcomeService/tutorList"
import BPIs from "common/src/api/welcomeService/schoolRelation"
import SchoolYear from './SchoolYear';
import SchoolMajorSelect from './SchoolMajorSelect';
import UTILS from "common/src/utils/utils";
import CPIs from "common/src/api/welcomeService/tutorExportImport"

const defaultCreateForm = {
  teacherCode:"",
  teacherName:"",
  sex:"",
  personnelCollege:"",
  faculty: "",
  majors: [],
  title:"",
  status:1,
  officePhone:"",
  telePhone:"",
  email:"",
  introduction:"",
  remark:"",
  photo:'',
  schoolId:'',
  grade:null,
  tutorType:"",
  major:''
};
// 本科生导师库
export default {
  name: "TutorSelf",
  props: ["tutorType"],
  computed: {},
  components: {
    SchoolYear,
    SchoolMajorSelect
  },
  mounted() {
    this.getOptions();
  },
  data() {
    return {
      key:'list',
      topTitle:'',
      addTitle:'',
      detailTitle:'',
      detialTitle:'',
      dialogVisible:false,
      loading1:false,
      defaultPhoto: "/static/images/icon_photo.png",
      api: CPIs,
      uploadUrl:'',
      message:"",
      isMultiple:false,
      editFaculty:false,
      imgUrl:'',
      options: {
        faculty: [],
        status:[
            {label:this.$t('tutorList.invalid'),value:0},{label:this.$t('tutorList.effective'),value:1}
        ],
        title:[],
        major:[],
        /* stuStatus:[
          {label:'未选择',value:0},{label:'已选择',value:1}
        ], */
        isAcross:[{label:this.$t('message.no'),value:0},{label:this.$t('message.yes'),value:1}],
        sex:[],
        school:[]
      },
      queryStu:{
        keyword:"",
        currentGrade:null,
        isOverseas:"",
        major:"",
        stuStatus:""
      },
      querySchool:{
        pageNum_:0,
        pageSize_:0,
        condition:{

        }
      },
      queryParams: {
        personnelCollege: '',
        faculty: '',
        major:'',
        title:'',
        status:'',
        isAcross:'',
        condition:'',
        type:"",
        grade:null
      },
      schoolMajor:[],
      collegeMajor:[],
      rules:{
        teacherCode: [
          {
            required: true,
            validator:this.checkTeacherCode,
            trigger: "blur"
          }
        ],
        faculty:[
          {
             required: true,
            message: this.$t("message.inputRequired"),
            trigger: "blur"
          }
        ],
        schoolId:[
          {
           required: true,
            message: this.$t("message.inputRequired"),
            trigger: "blur"
          }
        ],
        grade:[
          {
           required: true,
            message: this.$t("message.inputRequired"),
            trigger: "blur"
          }
        ],
        status:[
          {
           required: true,
            message: this.$t("message.inputRequired"),
            trigger: "blur"
          }
        ],
        grade:[
          {
           required: true,
            message: this.$t("message.inputRequired"),
            trigger: "blur"
          }
        ]
      },
      fileList:[],
      importFileList:[],
      createForm: UTILS.clone(defaultCreateForm),
      detailForm:UTILS.clone(defaultCreateForm)
    };
  },
  methods: {
    getOptions() {
      //筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: [
          "X_YX","profession","G_XBIE"
        ]
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
            {
              faculty: "X_YX",
              title:"profession",
              sex:"G_XBIE"
            },
            res.data,
            this.options
        );
        this.topTitle = this.tutorType == 1 ? '新生导师库' : '学院导师库'
        //学堂下拉
        BPIs.findSchool(this.querySchool).then(res =>{
          if(res.code==200 && res.data.list.length>0){
            for(const item of res.data.list){
              this.options.school.push({
                label:item.name,
                value:item.id
              });
            }
          }
        });
        this.searchList();
      });
    },
    transGrade (data){
      return data+'-'+(data+1)+'年度'
    },
    reback(data){
      if(!data){
        this.key = 'list';
        this.$nextTick(()=>{
          this.resetAddForm();
        });
      }else{
        if(data.id){
           this.key = 'list';
            this.$nextTick(()=>{
              this.resetAddForm();
            });
        }else{
            this.dialogVisible=true;
        }
      }
    },
    summit(){
      this.dialogVisible=false;
      this.key = 'list';
        this.$nextTick(()=>{
          this.resetAddForm();
        });
    },
    reset(){
        for(const key in this.queryParams){
            this.queryParams[key]=''
        }
        this.searchList();
    },
    checkTeacherCode(rule, value, callback) {
      if (!value) {
        callback(new Error(this.$t("message.inputRequired")));
      } else if (!this.createForm.teacherName) {
        callback(new Error(this.$t('Parameter.teacherNotExist')));
      } else {
        callback();
      }
    },
    getTeacherfo(){
      let code = this.createForm.teacherCode;
      if(!code){
        this.createForm = UTILS.clone(defaultCreateForm)
        return
      }
      //查找教师信息
      APIs.findTeacherByCode(code).then(res =>{
        if(res.code==200 && res.data){
          this.createForm.teacherCode=res.data.code;
          this.createForm.teacherName=res.data.name;
          this.createForm.sex=res.data.sex;
          this.createForm.title=res.data.title;
          this.createForm.personnelCollege=res.data.faculty;
          this.createForm.photo=res.data.photo;
          if(this.createForm.photo){
              this.findTutorPicture(this.createForm.photo)
          }
          this.$refs.createForm.clearValidate();
        }else{
          this.createForm = UTILS.clone(defaultCreateForm);
          this.createForm.teacherCode=code;
          this.$refs.createForm.validateField('teacherCode');
        }
      });
    },
    updateRecord(data) {
      this.imgUrl=''
      this.key='add'
      if(!data){//新增
          this.editFaculty = false;
          this.isMultiple=false;//多选
          if(this.tutorType==1){//校聘
              this.addTitle=this.$t("message.add")+'新生导师';
          }else{
              this.addTitle=this.$t("message.add")+'学院导师';
          }
          this.createForm = UTILS.clone(defaultCreateForm);
      }else{
          this.isMultiple=true;//单选
           if(this.tutorType==1){
              this.addTitle=this.$t("message.edit")+'新生导师';
            }else{
                this.addTitle=this.$t("message.edit")+'学院导师';
            }
          APIs.findTutorById(data.id).then(res =>{
            if(res.code==200){
              this.createForm = _.cloneDeep(res.data);
              if(this.createForm.actNum != 0){//有人，不让换导师所属学院
                this.editFaculty = true;
              }else{
                this.editFaculty = false;
              }
              if(this.createForm.photo){
               this.findTutorPicture(this.createForm.photo);
              }

              let that=this;
              setTimeout(() => {
                  that.createForm.major=res.data.major;
              }, 500);
            }
          });
          
          
      }
    },
    findTutorPicture(url){
       APIs.findPicture(url).then(res =>{
         if(res.code==200 && res.data){
            this.imgUrl = res.data.base;
         }else{
           this.imgUrl = this.defaultPhoto
         }
         
        });
    },
    getSchoolMajor(data){
      this.schoolMajor=data;
    },
    getAllMajor(data){
      this.collegeMajor=[];
      if( UTILS.isNotEmpty(data)){
          _.forEach(data, (d)=>{
          this.collegeMajor.push(d.value);
        });
      }
    },
    searchList() {
      this.queryParams.type = this.tutorType;
      this.$refs.mainTable.search(this.queryParams); 
    },
    resetAddForm() {
      this.searchList();
      this.$refs.createForm.clearValidate();
    },
    submitForm() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
          let item = UTILS.clone(this.createForm);
          item.type=this.tutorType;
          if (item.id) {//编辑
          if(!item.major){
            this.$message({
              type: "warning",
              message: '请选择专业'
            });
            return;
          }
            APIs.editTutor(item).then(response => {
              if (response.code == 200) {
                let message = this.$t("message.editSuccess");
                this.$message({
                  type: "success",
                  message: message
                });
              this.reback(null);
              }
            });
          } else {//新增
            if(UTILS.isEmpty(item.majors)){//全部
                if(this.tutorType== 1 ){//校聘
                  item.major=this.schoolMajor.join(",");
                }else{
                  item.major=this.collegeMajor.join(",");
                }
            }else{
              item.major=item.majors.join(",")
            }
            if(!item.major){
            this.$message({
                type: "warning",
                message: '请选择专业'
              });
              return;
            }
            APIs.addTutor(item).then(response => {
              if (response.code == 200) {
                let message = this.$t("message.addSuccess");
                this.$message({
                  type: "success",
                  message: message
                });
              this.reback(null);
              }
            });
          }
        }
      });
    },
    labelHead(h, { column, $index }) {
        return h("span", { attrs: { title: column.label } }, [
            column.label
        ]);
      }
  }
};
</script>
<style lang="scss" >
.stuTitle{
		line-height: 40px;
    width: 100%;
    border: 1px solid #CCE7FF;
    background-color: #EEF7FF;
    padding-left: 30px;
}
.picture{
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
